package main

import (
	"newAi/new_web/models"
	_ "newAi/new_web/routers"
	"fmt"

	"github.com/astaxie/beego"
	"io"
	"os"
	"github.com/astaxie/beego/plugins/cors"

	"flag"
	"net/http"
	"log"
)

func main() {
	defer func() {
		if err := recover(); err != nil {
			var filename = "./shutdown.txt"
			var f *os.File
			var err1 error
			/***************************** 第一种方式: 使用 io.WriteString 写入文件 ***********************************************/
			if checkFileIsExist(filename) { //如果文件存在
				f, err1 = os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
				//fmt.Println("文件存在")
			} else {
				f, err1 = os.Create(filename) //创建文件
				//fmt.Println("文件不存在")
			}
			fmt.Println(err1)
			_, _ = io.WriteString(f, err.(string))
			fmt.Println("here to shutdown  error:" + err.(string))
			f.Close()

			return
		}
	}()
	beego.AddFuncMap("eq64", models.Eqint64)
	models.Init()
	beego.SetStaticPath("/upload", "upload")
	beego.SetStaticPath("/views", "views")
	beego.SetStaticPath("/recordings", "recordings")
	beego.SetStaticPath("/vad_dir", "vad_dir")
	beego.SetStaticPath("/static", "static")
	beego.SetStaticPath("/sounddir", "sounddir")
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:    []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Content-Type"},
		ExposeHeaders:   []string{"Content-Length", "Access-Control-Allow-Origin"},
	}))
	
	beego.Run()
	var addr string
	flag.StringVar(&addr,"port","8099","8098")
	flag.Parse()
	server := http.FileServer(http.Dir("./views/dist"))
	log.Printf("server listen on: %s\n",addr)
	log.Fatal(http.ListenAndServe(addr,server))
}

func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}
